﻿using UnityEngine;
using System.Collections;
using System.Text;
using System.Collections.Generic;

namespace VFramework
{

	public class ScreenLogger : MonoBehaviour, ILogger
	{

		StringBuilder msg = new StringBuilder ();
		Vector2 scrollview = new Vector2 (Screen.width * 0.5f, 100);


		private object mutex = new object ();
		private Queue<object> msgQueue = new Queue<object> ();


		private ScreenLogger () { }

		public static ScreenLogger create (GameObject gameObj)
		{
			gameObj.AddComponent<ScreenLogger> ();
			return gameObj.GetComponent<ScreenLogger> ();
		}






		void pushMsg (object msg)
		{
			lock (mutex) {
				msgQueue.Enqueue (msg);
			}
		}

		void OnDistroy ()
		{

		}

		void Update ()
		{
			lock (mutex) {
				while (msgQueue.Count > 0) {
					onMessage (msgQueue.Dequeue ());
				}
			}
		}


		public void onMessage (object para)
		{
			if (msg.Length > 10240)
				msg.Remove (0, msg.Length);
			msg.AppendLine (para.ToString ());
		}

		void OnGUI ()
		{

			if (VLogger.getInstance ().isScreenLogClosed ()) {
				return;
			}

			GUI.backgroundColor = Color.gray;
			GUI.color = Color.black;
			scrollview = GUILayout.BeginScrollView (scrollview);
			GUILayout.Label (msg.ToString (), GUILayout.Width (scrollview.x));
			GUILayout.EndScrollView ();

		}
		public void doLog (string msg)
		{
			if (VLogger.getInstance ().isScreenLogClosed ()) {
				return;
			}

			pushMsg (msg);
		}
	}

}
